<template>
  <div class="device-management">
    <div class="page-header">
      <h2>设备管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索设备"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="showAddDeviceDialog">
          <el-icon><Plus /></el-icon> 添加设备
        </el-button>
      </div>
    </div>

    <el-table :data="filteredDevices" style="width: 100%">
      <el-table-column prop="name" label="设备名称" width="150" />
      <el-table-column prop="type" label="设备类型" width="120">
        <template #default="scope">
          {{ getDeviceTypeName(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="room" label="所在房间" width="120">
        <template #default="scope">
          {{ getRoomName(scope.row.roomId) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            @change="toggleDevice(scope.row)"
            :active-text="scope.row.status ? '开启' : '关闭'"
            :disabled="scope.row.updating"
          />
        </template>
      </el-table-column>
      <el-table-column label="设备参数">
        <template #default="scope">
          <div class="device-controls" v-if="scope.row.status">
            <!-- 灯光控制 -->
            <template v-if="scope.row.type === 'light'">
              <div class="control-item">
                <span class="param-label">亮度:</span>
                <el-slider
                  v-model="scope.row.brightness"
                  :min="1"
                  :max="100"
                  :step="1"
                  :show-input="true"
                  @change="(val) => updateDeviceProperty(scope.row, 'brightness', val)"
                  style="width: 200px"
                />
              </div>
            </template>

            <!-- 空调控制 -->
            <template v-if="scope.row.type === 'ac'">
              <div class="control-item">
                <span class="param-label">温度:</span>
                <el-input-number
                  v-model="scope.row.temperature"
                  :min="16"
                  :max="30"
                  :step="0.5"
                  @change="(val) => updateDeviceProperty(scope.row, 'temperature', val)"
                />
                <span class="param-label" style="margin-left: 20px">模式:</span>
                <el-select
                  v-model="scope.row.mode"
                  @change="(val) => updateDeviceProperty(scope.row, 'mode', val)"
                  style="width: 100px"
                >
                  <el-option label="制冷" value="cool" />
                  <el-option label="制热" value="heat" />
                  <el-option label="除湿" value="dry" />
                  <el-option label="送风" value="fan" />
                  <el-option label="自动" value="auto" />
                </el-select>
              </div>
            </template>

            <!-- 窗帘控制 -->
            <template v-if="scope.row.type === 'curtain'">
              <div class="control-item">
                <span class="param-label">开度:</span>
                <el-slider
                  v-model="scope.row.openness"
                  :min="0"
                  :max="100"
                  :step="1"
                  :show-input="true"
                  @change="(val) => updateDeviceProperty(scope.row, 'openness', val)"
                  style="width: 200px"
                />
              </div>
            </template>

            <!-- 热水器控制 -->
            <template v-if="scope.row.type === 'waterHeater'">
              <div class="control-item">
                <span class="param-label">温度:</span>
                <el-input-number
                  v-model="scope.row.temperature"
                  :min="35"
                  :max="75"
                  :step="1"
                  @change="(val) => updateDeviceProperty(scope.row, 'temperature', val)"
                />
                <span class="param-label" style="margin-left: 20px">模式:</span>
                <el-select
                  v-model="scope.row.mode"
                  @change="(val) => updateDeviceProperty(scope.row, 'mode', val)"
                  style="width: 120px"
                >
                  <el-option label="标准" value="normal" />
                  <el-option label="节能" value="eco" />
                  <el-option label="快速" value="quick" />
                  <el-option label="定时" value="timer" />
                </el-select>
              </div>
            </template>

            <!-- 冰箱控制 -->
            <template v-if="scope.row.type === 'fridge'">
              <div class="control-item">
                <span class="param-label">冷藏:</span>
                <el-input-number
                  v-model="scope.row.temperature"
                  :min="2"
                  :max="8"
                  :step="1"
                  @change="(val) => updateDeviceProperty(scope.row, 'temperature', val)"
                />
                <span class="param-label" style="margin-left: 20px">冷冻:</span>
                <el-input-number
                  v-model="scope.row.freezerTemp"
                  :min="-24"
                  :max="-16"
                  :step="1"
                  @change="(val) => updateDeviceProperty(scope.row, 'freezerTemp', val)"
                />
              </div>
            </template>
          </div>
          <el-tag v-else type="info" size="small">设备已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button
            type="danger"
            size="small"
            @click="handleDeleteDevice(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加设备对话框 -->
    <el-dialog
      v-model="addDeviceDialogVisible"
      title="添加设备"
      width="40%"
      :close-on-click-modal="false">
      <el-form
        :model="newDevice"
        :rules="rules"
        ref="deviceForm"
        label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="newDevice.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <el-select
            v-model="newDevice.type"
            placeholder="请选择设备类型"
            @change="handleDeviceTypeChange">
            <el-option
              v-for="type in deviceTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在房间" prop="roomId">
          <el-select
            v-model="newDevice.roomId"
            placeholder="请选择房间">
            <el-option
              v-for="room in rooms"
              :key="room.id"
              :label="room.name"
              :value="room.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 根据设备类型显示不同的初始配置选项 -->
        <template v-if="newDevice.type === 'light'">
          <el-form-item label="初始亮度">
            <el-slider v-model="newDevice.brightness" :min="1" :max="100"></el-slider>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'ac'">
          <el-form-item label="初始温度">
            <el-input-number v-model="newDevice.temperature" :min="16" :max="30" :step="0.5"></el-input-number>
          </el-form-item>
          <el-form-item label="初始模式">
            <el-select v-model="newDevice.mode">
              <el-option label="制冷" value="cool"></el-option>
              <el-option label="制热" value="heat"></el-option>
              <el-option label="除湿" value="dry"></el-option>
              <el-option label="送风" value="fan"></el-option>
              <el-option label="自动" value="auto"></el-option>
            </el-select>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'curtain'">
          <el-form-item label="初始开度">
            <el-slider v-model="newDevice.openness" :min="0" :max="100"></el-slider>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'waterHeater'">
          <el-form-item label="初始温度">
            <el-input-number v-model="newDevice.temperature" :min="35" :max="75"></el-input-number>
          </el-form-item>
          <el-form-item label="初始模式">
            <el-select v-model="newDevice.mode">
              <el-option label="标准" value="normal"></el-option>
              <el-option label="节能" value="eco"></el-option>
              <el-option label="快速" value="quick"></el-option>
              <el-option label="定时" value="timer"></el-option>
            </el-select>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'fridge'">
          <el-form-item label="冷藏温度">
            <el-input-number v-model="newDevice.temperature" :min="2" :max="8"></el-input-number>
          </el-form-item>
          <el-form-item label="冷冻温度">
            <el-input-number v-model="newDevice.freezerTemp" :min="-24" :max="-16"></el-input-number>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

export default {
  name: 'DeviceManagement',
  components: {
    Plus,
    Search
  },
  setup() {
    const store = useStore()
    const deviceForm = ref(null)
    const addDeviceDialogVisible = ref(false)
    const searchQuery = ref('')

    // 获取房间和设备类型列表
    const rooms = computed(() => store.state.rooms)
    const deviceTypes = computed(() => store.state.deviceTypes)

    // 获取所有设备列表
    const allDevices = computed(() => {
      return store.state.devices.devices.map(device => ({
        ...device,
        roomId: device.roomId
      }))
    })

    // 搜索过滤
    const filteredDevices = computed(() => {
      if (!searchQuery.value) return allDevices.value
      const query = searchQuery.value.toLowerCase()
      return allDevices.value.filter(device => 
        device.name.toLowerCase().includes(query) ||
        getDeviceTypeName(device.type).toLowerCase().includes(query) ||
        getRoomName(device.roomId).toLowerCase().includes(query)
      )
    })

    // 新设备表单数据
    const newDevice = ref({
      name: '',
      type: '',
      roomId: '',
      status: false,
      brightness: 50,
      temperature: 24,
      mode: 'normal',
      fanSpeed: 'auto',
      openness: 50,
      freezerTemp: -18
    })

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入设备名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择设备类型', trigger: 'change' }
      ],
      roomId: [
        { required: true, message: '请选择所在房间', trigger: 'change' }
      ]
    }

    // 获取设备类型名称
    const getDeviceTypeName = (typeId) => {
      const type = deviceTypes.value.find(t => t.id === typeId)
      return type ? type.name : typeId
    }

    // 获取房间名称
    const getRoomName = (roomId) => {
      const room = rooms.value.find(r => r.id === roomId)
      return room ? room.name : '未知房间'
    }

    // 重置新设备表单
    const resetNewDevice = () => {
      newDevice.value = {
        name: '',
        type: '',
        roomId: '',
        status: false,
        brightness: 50,
        temperature: 24,
        mode: 'normal',
        fanSpeed: 'auto',
        openness: 50,
        freezerTemp: -18
      }
      if (deviceForm.value) {
        deviceForm.value.resetFields()
      }
    }

    // 显示添加设备对话框
    const showAddDeviceDialog = () => {
      resetNewDevice()
      addDeviceDialogVisible.value = true
    }

    // 处理设备类型变化
    const handleDeviceTypeChange = (type) => {
      switch (type) {
        case 'light':
          newDevice.value.brightness = 50
          break
        case 'ac':
          newDevice.value.temperature = 24
          newDevice.value.mode = 'cool'
          newDevice.value.fanSpeed = 'auto'
          break
        case 'curtain':
          newDevice.value.openness = 50
          break
        case 'waterHeater':
          newDevice.value.temperature = 45
          newDevice.value.mode = 'normal'
          break
        case 'fridge':
          newDevice.value.temperature = 4
          newDevice.value.freezerTemp = -18
          newDevice.value.mode = 'normal'
          break
      }
    }

    // 添加设备
    const handleAddDevice = async () => {
      if (!deviceForm.value) return

      await deviceForm.value.validate((valid) => {
        if (valid) {
          const room = rooms.value.find(r => r.id === newDevice.value.roomId)
          if (!room) {
            ElMessage.error('所选房间不存在')
            return
          }

          store.dispatch('addDevice', {
            roomName: room.name,
            device: {
              name: newDevice.value.name,
              type: newDevice.value.type,
              ...getDeviceInitialProps(newDevice.value)
            }
          })

          // 触发设备列表更新
          store.dispatch('devices/fetchDevices');

          ElMessage.success('添加设备成功')
          addDeviceDialogVisible.value = false
        }
      })
    }

    // 获取设备初始属性
    const getDeviceInitialProps = (device) => {
      switch (device.type) {
        case 'light':
          return {
            brightness: device.brightness,
            status: device.status
          };
        case 'ac':
          return {
            temperature: device.temperature,
            mode: device.mode,
            fanSpeed: device.fanSpeed,
            status: device.status
          };
        case 'curtain':
          return {
            openness: device.openness,
            status: device.status
          };
        case 'waterHeater':
          return {
            temperature: device.temperature,
            mode: device.mode,
            status: device.status
          };
        case 'fridge':
          return {
            temperature: device.temperature,
            freezerTemp: device.freezerTemp,
            mode: device.mode,
            status: device.status
          };
        default:
          return { status: device.status };
      }
    };

    // 切换设备状态
    const toggleDevice = (device) => {
      store.dispatch('toggleDevice', device.id)
    }

    // 删除设备
    const handleDeleteDevice = (device) => {
      const room = rooms.value.find(r => r.id === device.roomId)
      if (!room) {
        ElMessage.error('设备所在房间不存在')
        return
      }

      ElMessageBox.confirm(
        `确定要删除设备"${device.name}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('removeDevice', {
          roomName: room.name,
          deviceId: device.id
        })
        ElMessage.success('删除成功')
      }).catch(() => {})
    }

    // 更新设备属性
    const updateDeviceProperty = (device, property, value) => {
      store.dispatch('updateDeviceProperty', {
        deviceId: device.id,
        property,
        value
      })
    }

    onMounted(() => {
      store.dispatch('devices/fetchDevices');
    });

    return {
      rooms,
      deviceTypes,
      filteredDevices,
      searchQuery,
      addDeviceDialogVisible,
      newDevice,
      deviceForm,
      rules,
      getDeviceTypeName,
      getRoomName,
      showAddDeviceDialog,
      handleDeviceTypeChange,
      handleAddDevice,
      toggleDevice,
      handleDeleteDevice,
      updateDeviceProperty
    }
  }
}
</script>

<style scoped>
.device-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.device-controls {
  padding: 5px 0;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 15px; /* 增加元素间距 */
}

.param-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  min-width: 40px;
  padding: 4px 6px; /* 增大内边距避免重叠 */
  line-height: 1.5; /* 调整行高优化显示 */
}

:deep(.el-form-item__content) {
  justify-content: flex-start;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-slider) {
  width: 100%;
}

:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light);
}

:deep(.el-table__row) {
  height: auto; /* 自动高度适应内容 */
  min-height: 80px; /* 保持最小高度 */
  padding: 8px 0; /* 增加行内边距 */
}
</style>